package com.phantasy.managers
{
	import com.phantasy.globals.GameParameters;
	
	import flash.utils.Dictionary;

	/**
	 *触发器 
	 * @author Liseen
	 * 
	 */	
	public class Dispatch
	{
		private static var instance:Dispatch;
		
		public var observers:Dictionary;
		private var mapping:Dictionary;

		public function Dispatch()
		{
			this.observers = new Dictionary();
			this.mapping = new Dictionary();
		}
		/**
		 *获取派发器 
		 * @return 
		 * 
		 */		
		public static function getInstance():Dispatch
		{
			if(!instance)
			{
				instance = new Dispatch();
			}
			
			return instance;
		}
		/**
		 *派发 
		 * @param type	消息类型
		 * @param data	消息数据
		 * 
		 */		
		public static function dispatch(type:String, param:Object=null):void
		{
			getInstance().execute(type, param);
		}
		/**
		 *注册模块侦听 
		 * @param type			类型
		 * @param callBack		回调
		 * @param module
		 * @param method
		 * 
		 */		
		public static function register(type:String, callBack:Function, module:String=null, method:String=null):void
		{
			getInstance().add(type, callBack, module, method);
		}
		
		public static function remove(type:String, callBack:Function):void
		{
			getInstance().remove(type, callBack);
		}
		
		
		private function add(type:String, callBack:Function, module:String=null, method:String=null):void
		{
			var _local5:Array = this.observers[type];
			this.mapping[callBack] = {
				"module":module,
				"method":method
			}
			if (_local5 == null)
			{
				_local5 = [];
				this.observers[type] = _local5;
			}
			else
			{
				if (_local5.indexOf(callBack) != -1)
				{
					return;
				}
			}
			_local5.push(callBack);
		}
		
		private function remove(_arg1:String, _arg2:Function):void
		{
			var _local4:int;
			var _local3:Array = this.observers[_arg1];
			if (_local3)
			{
				_local4 = _local3.indexOf(_arg2);
				if (_local4 != -1)
				{
					_local3.splice(_local4, 1);
				};
			};
		}
		
		private function execute(type:String,param:Object):void
		{
			var call:Function;
			var obj:Object;
			var funcs:Array = this.observers[type];
			for each (call in funcs)
			{
				if (GameParameters.getInstance().isDebug())
				{
					if (param == null)
					{
						call.apply(null, null);
					}
					else
					{
						call.apply(null, [param]);
					}
				}
				else
				{
					try
					{
						if (param == null)
						{
							call.apply(null, null);
						}
						else
						{
							call.apply(null, [param]);
						}
					}
					catch(e:Error)
					{
						obj = mapping[call];
						
					}
				}
			}
		}
	}
}